package com.ks.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ks.entity.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ks.base.BaseAction;
import com.ks.service.ContentQuestionService;
import com.ks.service.ContentService;
import com.ks.service.DepositoryService;
import com.ks.service.ExamParenttypeService;
import com.ks.service.QuestionService;
import com.ks.service.QuestiontypeService;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Huangzy 题库管理
 */
@Controller
@RequestMapping("/depository")
public class DepositoryController extends BaseAction {
	@Autowired
	private ExamParenttypeService<ExamParenttype> examParenttypeService;
	@Autowired
	private DepositoryService<Depository> depositoryService;
	@Autowired
	private ContentService<Content> contentService;
	@Autowired
	private QuestiontypeService<Questiontype> questiontypeService;
	@Autowired
	private QuestionService<Question> questionService;
	@Autowired
	private ContentQuestionService contentQuestionService;

	/**
	 * 跳转到题库管理页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toPage")
	public String toPage(Model model, HttpServletRequest request, HttpServletResponse response) {

		List<Depository> depList = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("orderCondition", "");
		map.put("mysqlQueryCondition", "");
		try {
			// 查询题库列表
			depList = depositoryService.queryByList(map);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			sendFailureMessage(response, e.getMessage());
		}
		model.addAttribute("depList", depList);
		return "pages/depository/item-list";
	}

	/**
	 * 跳转到新增题库页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toAddPage")
	public String toAddPage(Model model, HttpServletRequest request, HttpServletResponse response) {
		List<ExamParenttype> typeList = new ArrayList<>();

		Map<String, Object> map = new HashMap<>();
		map.put("orderCondition", "");
		map.put("mysqlQueryCondition", "");
		try {
			// 查询考试大类列表
			typeList = examParenttypeService.queryByList(map);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			sendFailureMessage(response, e.getMessage());
		}
		model.addAttribute("typeList", typeList);
		return "pages/depository/item-add";
	}

	/**
	 * 新增题库
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("addDepository")
	@ResponseBody
	public Map<String, Object> addDepository(@RequestParam("file_upload") MultipartFile file,
			HttpServletRequest request, HttpServletResponse response) {

		String title = request.getParameter("title");
		String type = request.getParameter("type");
		String description = request.getParameter("description");
		String relativePath = depositoryService.uploadImg(file, "depository");
		String msg = "";
		Map<String, Object> dataMap = new HashMap<>();
		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Depository depository = (Depository) ac.getBean("depository");
		depository.setName(title);
		depository.setType_id(Integer.parseInt(type));
		depository.setDescription(description);
		depository.setPicture(relativePath);
		depository.setCreatetime(new Date());
		try {
			depositoryService.add(depository);
			dataMap.put("status", "1");
			msg = "添加成功！";
			dataMap.put("picPath", relativePath);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			dataMap.put("status", "0");
			msg = "添加失败:" + e.getMessage();
		}
		dataMap.put("msg", msg);
		return dataMap;
	}

	/**
	 * 删除题库
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("delDep")
	@ResponseBody
	public Map<String, Object> delDep(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String depId = request.getParameter("depId");
		Map<String, Object> resultMap = new HashMap<>();
		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Content content = (Content) ac.getBean("content");
		Depository depository = (Depository) ac.getBean("depository");
		depository.setId(Integer.parseInt(depId));
		String msg = "";
		content.setDesp_id(Integer.parseInt(depId));
		List<Content> contentList = contentService.queryList(content);
		if (contentList.size()>0){
			resultMap.put("status", 0);
			msg = "该题库中含有章节,不能删除！";
		} else {
			depositoryService.del(depository);
			resultMap.put("status", 1);
			msg = "操作成功！";
		}
		resultMap.put("msg", msg);
		return resultMap;
	}

	/**
	 * 跳转到题库详情页面
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("toKnows")
	public ModelAndView toKnows(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 查询题库信息
		String depId = request.getParameter("depId");
		Map<String, Object> map =depositoryService.toKnows(depId);
		return forword("pages/depository/item-knows", map);
	}

	@RequestMapping("toKnowsAjax")
	@ResponseBody
	public List<Content> toKnowsAjax(HttpServletRequest request, HttpServletResponse response) {
		String depId = request.getParameter("depId");
		String keyword = request.getParameter("keyword");
		Map<String, Object> map = new HashMap<>();
		map.put("depId", depId);
		map.put("keyword", keyword);
		return contentService.toKnowsAjax(map);
	}

	/**
	 * 跳转到编辑页面
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toEdit")
	public String toEdit(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		String depId = request.getParameter("depId");
		String conId = request.getParameter("conId");
		String tempId = "";
		if (StringUtils.isNotBlank(depId)) {
			tempId = depId;
		} else {
			tempId = conId;
		}

		List<ExamParenttype> typeList = new ArrayList<>();
		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Depository depository = (Depository) ac.getBean("depository");
		depository = (Depository) depositoryService.queryById(tempId);
		model.addAttribute("depo", depository);

		// 获取考试大类列表
		Map<String, Object> map = new HashMap<>();
		map.put("orderCondition", "");
		map.put("mysqlQueryCondition", "");
		typeList = examParenttypeService.queryByList(map);

		model.addAttribute("typeList", typeList);
		model.addAttribute("depo", depository);
		model.addAttribute("label", "edit");
		return "pages/depository/item-add";
	}

	/**
	 * 更新题库基本信息
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("updateDepo")
	@ResponseBody
	public Map<String, Object> updateDepo(@RequestParam("file_upload") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String id = request.getParameter("id");
		String title = request.getParameter("title");
		String type = request.getParameter("type");
		String description = request.getParameter("description");
		String relativePath = depositoryService.uploadImg(file, "depository");
		String msg = "";
		Map<String, Object> dataMap = new HashMap<>();
		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Depository depository = (Depository) ac.getBean("depository");
		Depository depository2 = (Depository) ac.getBean("depository");
		depository.setName(title);
		depository.setType_id(Integer.parseInt(type));
		depository.setDescription(description);
		if (StringUtils.isNotBlank(relativePath)) {
			depository.setPicture(relativePath);
		}
		depository.setCreatetime(new Date());
		depository.setId(Integer.parseInt(id));

		try {
			depositoryService.updateBySelective(depository);
			depository2 = depositoryService.queryById(Integer.parseInt(id));
			dataMap.put("status", "1");
			msg = "修改成功！";
			dataMap.put("picPath", depository2.getPicture());
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			dataMap.put("status", "0");
			msg = "修改失败:" + e.getMessage();
		}
		dataMap.put("msg", msg);
		return dataMap;
	}

	/**
	 * 添加章节
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("addContent")
	@ResponseBody
	public Map<String, Object> addContent(HttpServletRequest request, HttpServletResponse response) {
		String name = request.getParameter("contentName");
		String depoId = request.getParameter("depId");
		String pro = request.getParameter("pro");
		String rank = request.getParameter("rank");
		Map<String, Object> map = new HashMap<>();
		String msg = "";

		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Content content = (Content) ac.getBean("content");
		content.setDesp_id(Integer.parseInt(depoId));
		content.setTitle(name);
		if (StringUtils.isNotBlank(pro) && !"0".equals(pro)) {
			content.setPro_id(Integer.parseInt(pro));
		}
		if (StringUtils.isNotBlank(rank) && !"0".equals(rank)) {
			content.setRank_id(Integer.parseInt(rank));
		}
		try {
			contentService.add(content);
			map.put("status", 1);
			map.put("conId", content.getId());
			msg = "添加成功！";
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			map.put("status", 0);
			msg = "添加失败：" + e.getMessage();
		}
		map.put("msg", msg);
		return map;
	}

	/**
	 * 删除章节
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("delContent")
	@ResponseBody
	public Map<String, Object> delContent(HttpServletRequest request, HttpServletResponse response) throws Exception{
		String conId = request.getParameter("conId");
		Map<String, Object> map = new HashMap<>();
		String msg = "";
		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Content content = (Content) ac.getBean("content");
		content.setId(Integer.parseInt(conId));
		ContentQuestion contentQuestion = (ContentQuestion) ac.getBean("contentQuestion");
		contentQuestion.setContent_id(Integer.parseInt(conId));
		List<ContentQuestion> questionList = contentQuestionService.queryList(contentQuestion);
		if(questionList.size()>0) {
			map.put("status", 0);
			msg = "本章节下有试题不允许删除！";
		}else{
			contentService.del(content);
			map.put("status", 1);
			msg = "删除成功！";
		}
		map.put("msg", msg);
		return map;

	}

	/**
	 * 编辑章节
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("editContent")
	@ResponseBody
	public Map<String, Object> editContent(HttpServletRequest request, HttpServletResponse response) {
		String contName = request.getParameter("contName");
		String contId = request.getParameter("contId");
		String pro = request.getParameter("pro");
		String rank = request.getParameter("rank");
		Map<String, Object> map = new HashMap<String, Object>();
		String msg = "";

		ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
		Content content = (Content) ac.getBean("content");
		content.setId(Integer.parseInt(contId));
		content.setTitle(contName);
		if (StringUtils.isNotBlank(pro)) {
			content.setPro_id(Integer.parseInt(pro));
		}
		if (StringUtils.isNotBlank(rank)) {
			content.setRank_id(Integer.parseInt(rank));
		}

		try {
			contentService.updateBySelective(content);
			map.put("status", "1");
			msg = "修改成功！";
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			map.put("status", "0");
			msg = "修改失败:" + e.getMessage();
		}
		map.put("msg", msg);
		return map;

	}

	/**
	 * 跳转到添加试题页面
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toAddQuestions")
	public ModelAndView toAddQuestions(Model model, HttpServletRequest request, HttpServletResponse response) {
		String conId = request.getParameter("conId");
		Map<String, Object> map = new HashMap<>();
		// 查询试题类型列表
		map = depositoryService.toCheckQuestions(conId);
		map.put("conId", conId);
		return forword("pages/depository/item-addquestion", map);
	}

	/**
	 * 跳转到添加某道题页面
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toAddQuestion")
	public String toAddQuestion(Model model, HttpServletRequest request, HttpServletResponse response) {
		String typeId = request.getParameter("typeId");//题型id
		String conId = request.getParameter("conId");//知识点id

		List<Questiontype> quList = new ArrayList<Questiontype>();

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("orderCondition", "");
		map.put("mysqlQueryCondition", "");

		// 查询试题类型列表
		try {
			quList = questiontypeService.queryByList(map);
			model.addAttribute("quList", quList);
			model.addAttribute("typeId", typeId);
			model.addAttribute("conId", conId);
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			sendFailureMessage(response, e.getMessage());
		}

		return "pages/depository/item-question-add";
	}

	/**
	 * 添加试题
	 * 
	 * @param picture
	 * @param ana_picture
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("addQuestion")
	@ResponseBody
	public Map<String, Object> addQuestion(@RequestParam("picture") MultipartFile picture,
			@RequestParam("ana_picture") MultipartFile ana_picture, HttpServletRequest request,
			HttpServletResponse response) {

		String size = request.getParameter("size");//长度
		String answer = request.getParameter("answer");//正确答案是第几个 0 1 2 3 没有就是 -1
		String ansStr = request.getParameter("answerArray");//是null
		// 获取题目信息
		String title = request.getParameter("title");//题目
		String description = request.getParameter("description");//解析
		String typeId = request.getParameter("typeId");//
		String type = request.getParameter("type");
		String conId = request.getParameter("conId");
		



		return depositoryService.addQuestion(size, answer, ansStr, title, description, typeId, type, conId, request,
				picture, ana_picture);

	}

	/**
	 * 跳转到查询不同类型题页面
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toCheckQuestions")
	public ModelAndView toCheckQuestions(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception{
		String conId = request.getParameter("conId");
		Map<String, Object> map = depositoryService.toCheckQuestions(conId);
		//根据知识点查询题库
		map.put("conId", conId);
		Content content = contentService.queryById(conId);
		map.put("depId", content.getDesp_id());
		return forword("pages/depository/item-type", map);
	}

	/**
	 * 跳转到查看某个类型的题页面
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toCheckQuestion")
	public String toCheckQuestion(Model model, HttpServletRequest request, HttpServletResponse response) {
		String typeId = request.getParameter("typeId");//题型id
		String ConId = request.getParameter("ConId");//题库的id
		String page_num = request.getParameter("page_num");
		String page_size = request.getParameter("page_size");
		String typeCount = request.getParameter("typeCount");
		String keyword = request.getParameter("keyword");
		// paper_questiontype表 questiontypeid
		String questiontypeId = request.getParameter("questiontypeId");//前台传过来null 不知道有没有用
		depositoryService
				.toCheckQuestion(model, typeId, ConId, page_num, page_size, typeCount, questiontypeId, keyword);
		return "pages/depository/item-view";
	}

	/**
	 * 分页查询试题
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toCheckQuestionAjax")
	@ResponseBody
	public Map<String, Object> toCheckQuestionAjax(HttpServletRequest request, HttpServletResponse response) {

		String typeId = request.getParameter("typeId");
		String ConId = request.getParameter("ConId");
		String page_num = request.getParameter("page_num");
		String page_size = request.getParameter("page_size");
		return depositoryService.toCheckQuestionAjax(typeId, ConId, page_num, page_size);

	}

	/**
	 * 删除试题
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("delQuestion")
	@ResponseBody
	public Map<String, Object> delQuestion(HttpServletRequest request, HttpServletResponse response) throws Exception{

		String delQuestionStr = request.getParameter("delQuestionStr");
		Map<String, Object> dataMap = new HashMap<String, Object>();
		String msg = "";
		if (StringUtils.isNotBlank(delQuestionStr)) {
			delQuestionStr = delQuestionStr.substring(0, delQuestionStr.length() - 1);
		}
		String[] quIds = delQuestionStr.split(",");

		questionService.delete(quIds);
		dataMap.put("status", 1);
		msg = "删除成功！";
		dataMap.put("msg", msg);
		return dataMap;

	}

	/**
	 * 跳转到更新试题页面
	 * 
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("toUpdateQuestion")
	public String toUpdateQuestion(Model model, HttpServletRequest request, HttpServletResponse response) {
		String questionId = request.getParameter("questionId");
		depositoryService.toUpdateQuestion(model, questionId);
		return "pages/depository/item-question-add";
	}

	/**
	 * 编辑试题
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("updateQuestion")
	@ResponseBody
	public Map<String, Object> updateQuestion(@RequestParam("picture") MultipartFile picture,
			@RequestParam("ana_picture") MultipartFile ana_picture, HttpServletRequest request,
			HttpServletResponse response) {
		String questionId = request.getParameter("questionId");
		String size = request.getParameter("size");
		String answer = request.getParameter("answer");
		String ansStr = request.getParameter("answerArray");
		// 获取题目信息
		String title = request.getParameter("title");
		String description = request.getParameter("description");
		String typeId = request.getParameter("typeId");
		String type = request.getParameter("type");
		return depositoryService.updateQuestion(questionId, size, answer, ansStr, title, description, typeId, type,
				request, picture, ana_picture);
	}

	/**
	 * 导入试题
	 * 
	 * @param file
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("importQuestions")
	@ResponseBody
	public Map<String, Object> importQuestions(@RequestParam("myFile") MultipartFile file, HttpServletRequest request,
			HttpServletResponse response) {
		String conId = request.getParameter("conId");
		return depositoryService.importQuestions(file, conId);
	}

	/**
	 * 根据专业id联动查询级别
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("getRanksByPro")
	@ResponseBody
	public Map<String, Object> getRanksByPro(HttpServletRequest request, HttpServletResponse response) {
		String proId = request.getParameter("proId");
		return depositoryService.getRanksByPro(proId);
	}
}
